package gui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

public class ToolModify extends Tool {
	Point p = new Point(0, 0);
	UI_Node n = null;
	UI_Branch b = null;
	boolean movingNode;

	@Override
	public void select(MainFrame mainFrame) {
		mainFrame.status("Modify tool selected...");
	}

	@Override
	public void keyType(MainFrame thisFrame, UI_SFG graph, KeyEvent e, boolean done) {}

	@Override
	public void mouseClick(MainFrame f, UI_SFG graph, MouseEvent e, MyView v) {
		int btn = e.getButton();
		if (btn == MouseEvent.BUTTON1) {
			if (!movingNode) {
				if (n != null) {
					movingNode = true;
					p = n.pos();
				}
			} else {
				movingNode = false;
				p = new Point(e.getX(), e.getY());
			}
		} else if (btn == MouseEvent.BUTTON3) {
			if (!isBusy()) {
				if (n != null)
					graph.removeNode(n);
				else if (b != null) {
					graph.disconnect(b);
					b = null;
				}
			}
		}
	}

	@Override
	public void mouseMove(MainFrame f, UI_SFG graph, MouseEvent e, int dX, int dY, MyView v) {
		p.x = e.getX();
		p.y = e.getY();
		UI_Branch snapB = snapBranch(f, graph, p);
		if (!movingNode)
			b = snapB;
		UI_Node snap = snap(f, graph, p, n);
		if (!movingNode)
			n = snap;
	}

	@Override
	public void mouseDrag(MainFrame f, UI_SFG graph, MouseEvent e, int dX, int dY, MyView v) {
		mouseMove(f, graph, e, dX, dY, v);
	}

	@Override
	public Cursor cursor() {
		if (movingNode)
			return Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);
		else if (n != null)
			return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
		else
			return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
	}

	@Override
	public void paint(MainFrame mainFrame, UI_SFG graph, Graphics2D g, MyView v) {
		if (n != null) {
			g.setColor(Color.ORANGE);
			n.paint(g, v);
		}
		if (b != null) {
			g.setColor(Color.ORANGE);
			b.paint(g, v);
		}
		g.setColor(Color.RED);
	}

	@Override
	public boolean isBusy() {
		return movingNode;
	}

	@Override
	public void clear(MainFrame f, UI_SFG graph) {
		movingNode = false;
		p = new Point(0, 0);
		b = null;
	}

}
